package com.wesley.framework.protocol.dubbo;

import com.wesley.framework.Invocation;
import com.wesley.framework.register.LocalRegister;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * NettyServerHandler
 *
 * @author WangPanYong
 * @since 2021/11/17 14:05
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 上线了" + "\n");
    }

    /**
     * 根据 客户端 发送的调用信息，反射调用实现类
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(" 接收到客户端数据: "+ msg);
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        Invocation invocation = ProtostuffUtil.deserializer(bytes, Invocation.class);

        Class serviceImpl = LocalRegister.get(invocation.getInterfaceName());

        Method method = serviceImpl.getMethod(invocation.getMethodName(), invocation.getParamTypes());
        Object result = method.invoke(serviceImpl.newInstance(), invocation.getParams());

        System.out.println(" Netty ====> " + result.toString());
        ByteBuf resByte = Unpooled.copiedBuffer(ProtostuffUtil.serializer(result));
        ctx.writeAndFlush(resByte);
    }

}
